<%@ page isELIgnored="true" language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生考试系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

    <!-- Tailwind配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#0FC6C2',
                        accent: '#722ED1',
                        warning: '#FF7D0000',
                        danger: '#F53F3F',
                        success: '#00B42A',
                        info: '#86909C',
                        light: '#F2F3F5',
                        dark: '#1D2129',
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .sidebar-icon {
                @apply relative flex items-center justify-center h-10 w-10 mt极-2 mb-2 mx-auto
                bg-gray-800 hover:bg-primary hover:text-white
                rounded-3xl hover:rounded-xl
                transition-all duration-300 ease-linear
                cursor-pointer shadow-lg;
            }
            .sidebar-tooltip {
                @apply absolute w-auto p-2 m-2 min-w-max left-14 rounded-md shadow-md
                text-white bg-gray-900
                text-xs font-bold
                transition-all duration-100 scale-0 origin-left;
            }
            .btn-primary {
                @apply bg-primary hover:bg-primary/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-secondary {
                @apply bg-gray-200 hover:bg-gray-300 text-gray-800 font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-danger {
                @apply bg-danger hover:bg-danger/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-warning {
                @apply bg-warning hover:bg-warning/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .btn-success {
                @apply bg-success hover:bg-success/90 text-white font-medium py-2 px-4 rounded-lg transition-all duration-200;
            }
            .card {
                @apply bg-white rounded-xl shadow-md p-5 transition-all duration-300 hover:shadow-lg;
            }
            .input-field {
                @apply w-full px-4 py-2 mt-2 mb-4 text-gray-700 bg-white border border-gray-300 rounded-lg focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-200 outline-none;
            }
            .table-row {
                @apply transition-all duration-200 hover:bg-gray-50;
            }
            .badge {
                @apply px-2 py-1 text-xs rounded-full font-medium;
            }
            .status-badge {
                @apply px-3 py-1 rounded-full text-sm font-medium;
            }
        }
    </style>
</head>
<body class="bg-gray-100 font-inter antialiased text-gray-800">
<div class="flex h-screen overflow-hidden">
    <!-- 侧边栏导航 -->
    <div class="hidden md:flex md:flex-col md:w-64 md:fixed md:inset-y-0 bg-dark border-r border-gray-800 z-30 transition-all duration-300 ease-in-out" id="sidebar">
        <!-- 学生信息 -->
        <div class="flex items-center justify-center h-16 border-b border-gray-800">
            <div class="flex items-center">
                <div class="h-10 w-10 rounded-full bg-primary flex items-center justify-center">
                    <i class="fa fa-user-graduate text-white text-xl"></i>
                </div>
                <div class="ml-3">
                    <p class="text-white font-semibold" id="student-name">加载中...</p>
                    <p class="text-gray-400 text-xs" id="student-class">加载中...</p>
                </div>
            </div>
        </div>

        <!-- 导航菜单 -->
        <nav class="flex-1 overflow-y-auto py-4 px-3">
            <div class="space-y-1">
                <a href="#dashboard" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg bg-primary/10 text-primary group">
                    <i class="fa fa-tachometer w-5 h-5 mr-3"></i>
                    <span>控制面板</span>
                </a>
                <a href="#exam" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                    <i class="fa fa-file-text-o w-5 h-5 mr-3"></i>
                    <span>在线考试</span>
                </a>
                <a href="#grades" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                    <i class="fa fa-bar-chart w-5 h-5 mr-3"></i>
                    <span>成绩查询</span>
                </a>
                <a href="#account" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                    <i class="fa fa-user w-5 h-5 mr-3"></i>
                        <span>账户管理</span>
                </a>
            </div>
        </nav>

        <!-- 退出登录 -->
        <div class="border-t border-gray-800 p-4">
            <a href="logout" class="flex items-center px-3 py-2 text-sm font-medium rounded-lg text-gray-300 hover:bg-gray-700 hover:text-white group">
                <i class="fa fa-sign-out w-5 h-5 mr-3"></i>
                <span>退出登录</span>
            </a>
        </div>
    </div>

    <!-- 移动端侧边栏按钮 -->
    <div class="md:hidden fixed top-4 left-4 z-50">
        <button id="sidebar-toggle" class="p-2 rounded-md text-gray-600 hover:text-white hover:bg-primary focus:outline-none">
            <i class="fa fa-bars text-xl"></i>
        </button>
    </div>

    <!-- 主内容区域 -->
    <div class="flex-1 flex flex-col overflow-hidden ml-0 md:ml-64 transition-all duration-300 ease-in-out">
        <!-- 顶部导航栏 -->
        <header class="bg-white shadow-sm z-20">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex items-center">
                        <div class="flex-shrink-0 flex items-center">
                            <h1 class="text-xl font-semibold text-primary">学生考试系统</h1>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <div class="flex-shrink-0">
                            <button id="change-password-btn" class="bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium py-2 px-4 rounded-lg transition-all duration-200 flex items-center">
                                <i class="fa fa-key mr-2"></i> 修改密码
                            </button>
                        </div>
                        <div class="ml-4 flex items-center md:ml-6">
                            <button class="p-1 rounded-full text-gray-500 hover:text-primary focus:outline-none">
                                <span class="sr-only">查看通知</span>
                                <i class="fa fa-bell-o text-xl"></i>
                            </button>
                            <div class="ml-3 relative">
                                <div class="flex items-center">
                                    <div class="h-8 w-8 rounded-full bg-primary flex items-center justify-center">
                                        <i class="fa fa-user text-white"></i>
                                    </div>
                                    <span class="ml-2 text-sm font-medium text-gray-700 hidden md:block" id="top-student-name">加载中...</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </header>

        <!-- 页面内容 -->
        <main class="flex-1 overflow-y-auto bg-gray-100 p-4 sm:p-6 lg:p-8">
            <!-- 控制面板 -->
            <section id="dashboard-section" class="space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">控制面板</h2>
                        <p class="mt-1 text-sm text-gray-500" id="welcome-message">欢迎回来，请稍候...</p>
                    </div>
                    <div class="mt-4 flex md:mt-0 md:ml-4">
                        <button type="button" class="btn-secondary" id="refresh-dashboard">
                            <i class="fa fa-refresh mr-2"></i> 刷新数据
                        </button>
                    </div>
                </div>

                <!-- 数据概览卡片 -->
                <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6" id="dashboard-cards">
                    <!-- 卡片内容将通过AJAX填充 -->
                </div>

                <!-- 最近考试区域 -->
                <div class="grid grid-cols-1 gap-6">
                    <div class="card">
                        <div class="flex items-center justify-between mb-6">
                            <h3 class="text-lg font-semibold text-gray-900">近期考试安排</h3>
                            <button class="text-gray-400 hover:text-gray-600">
                                <i class="fa fa-ellipsis-v"></i>
                            </button>
                        </div>
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试名称</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试时间</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                                </tr>
                                </thead>
                                <tbody id="exam-list" class="bg-white divide-y divide-gray-200">
                                <!-- 考试列表将通过AJAX填充 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 在线考试模块 -->
            <section id="exam-section" class="hidden space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">在线考试</h2>
                        <p class="mt-1 text-sm text-gray-500">参加已激活的考试</p>
                    </div>
                    <div class="mt-4 flex md:mt-0 md:ml-4">
                        <button type="button" class="btn-secondary" id="refresh-exams">
                            <i class="fa fa-refresh mr-2"></i> 刷新列表
                        </button>
                    </div>
                </div>

                <!-- 考试列表 -->
                <div class="card">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试名称</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试时间</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                <th scope="col" class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                            </tr>
                            </thead>
                            <tbody id="available-exam-list" class="bg-white divide-y divide-gray-200">
                            <!-- 可参加考试列表将通过AJAX填充 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- 成绩查询模块 -->
            <section id="grades-section" class="hidden space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">成绩查询</h2>
                        <p class="mt-1 text-sm text-gray-500">查看个人考试成绩</p>
                    </div>
                    <div class="mt-4 flex md:mt-0 md:ml-4">
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-search text-gray-400"></i>
                            </div>
                            <input type="text" id="grade-search" class="pl-10 input-field w-64" placeholder="搜索课程...">
                        </div>
                        <button id="search-grades" class="btn-primary ml-2">
                            <i class="fa fa-search mr-2"></i> 搜索
                        </button>
                    </div>
                </div>

                <div class="grid grid-cols-1 gap-6">
                    <div class="card">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">成绩概览</h3>
                        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
                            <div class="bg-green-50 p-4 rounded-lg">
                                <p class="text-sm text-green-800">已通过课程</p>
                                <p class="text-2xl font-bold text-green-800" id="passed-count">0</p>
                            </div>
                            <div class="bg-red-50 p-4 rounded-lg">
                                <p class="text-sm text-red-800">未通过课程</p>
                                <p class="text-2xl font-bold text-red-800" id="failed-count">0</p>
                            </div>
                            <div class="bg-blue-50 p-4 rounded-lg">
                                <p class="text-sm text-blue-800">平均分</p>
                                <p class="text-2xl font-bold text-blue-800" id="average-score">0</p>
                            </div>
                        </div>
                    </div>

                    <!-- 成绩列表 -->
                    <div class="card">
                        <div class="overflow-x-auto">
                            <table class="min-w-full divide-y divide-gray-200">
                                <thead class="bg-gray-50">
                                <tr>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">课程名称</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试名称</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">成绩</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                                    <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">考试时间</th>
                                </tr>
                                </thead>
                                <tbody id="grade-list" class="bg-white divide-y divide-gray-200">
                                <!-- 成绩列表将通过AJAX填充 -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </section>

            <!-- 账户管理模块 -->
            <section id="account-section" class="hidden space-y-6">
                <div class="flex flex-col md:flex-row md:items-center md:justify-between">
                    <div>
                        <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-900">账户管理</h2>
                        <p class="mt-1 text-sm text-gray-500">管理您的账户信息和安全设置</p>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <!-- 个人信息 -->
                    <div class="card">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">个人信息</h3>
                        <form id="profile-form" method="POST" action="StudentProfileUpdateServlet">
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">学号</label>
                                    <input type="text" id="student_no" class="input-field bg-gray-100" disabled>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">姓名</label>
                                    <input type="text" id="student_name" class="input-field bg-gray-100" disabled>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">班级</label>
                                    <input type="text" id="class_name" class="input-field bg-gray-100" disabled>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">电话</label>
                                    <input type="tel" name="phone" id="phone" class="input-field">
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">邮箱</label>
                                    <input type="email" name="email" id="email" class="input-field">
                                </div>
                                <button type="submit" class="btn-primary w-full">更新个人信息</button>
                            </div>
                        </form>
                    </div>

                    <!-- 修改密码 -->
                    <div class="card">
                        <h3 class="text-lg font-medium text-gray-900 mb-4">修改密码</h3>
                        <form id="password-form">
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">当前密码</label>
                                    <input type="password" name="current-password" class="input-field" placeholder="请输入当前密码" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">新密码</label>
                                    <input type="password" name="new-password" class="input-field" placeholder="请输入新密码" required>
                                </div>
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-1">确认新密码</label>
                                    <input type="password" name="confirm-password" class="input-field" placeholder="请再次输入新密码" required>
                                </div>
                                <div class="text-sm text-gray-500">
                                    <p>密码要求：</p>
                                    <ul class="list-disc pl-5 mt-1">
                                        <li>至少8个字符</li>
                                        <li>包含字母和数字</li>
                                        <li>可包含特殊字符</li>
                                    </ul>
                                </div>
                                <button type="submit" class="btn-primary w-full">修改密码</button>
                            </div>
                        </form>
                    </div>
                </div>
            </section>
        </main>
    </div>
</div>

<!-- 修改密码模态框 -->
<div id="change-password-modal" class="fixed inset-0 bg-black bg-opacity-50 z-50 hidden">
    <div class="min-h-screen flex items-center justify-center p-4">
        <div class="bg-white rounded-lg max-w-md w-full mx-auto p-6 transform transition-all">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-lg font-medium text-gray-900">修改密码</h3>
                <button id="close-password-modal" class="text-gray-400 hover:text-gray-500">
                    <i class="fa fa-times"></i>
                </button>
            </div>
            <form id="modal-password-form">
                <div class="mb-4">
                    <label for="current-password" class="block text-sm font-medium text-gray-700">当前密码</label>
                    <input type="password" id="current-password" name="current-password" class="input-field" required>
                </div>
                <div class="mb-4">
                    <label for="new-password" class="block text-sm font-medium text-gray-700">新密码</label>
                    <input type="password" id="new-password" name="new-password" class="input-field" required>
                </div>
                <div class="mb-6">
                    <label for="confirm-password" class="block text-sm font-medium text-gray-700">确认新密码</label>
                    <input type="password" id="confirm-password" name="confirm-password" class="input-field" required>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancel-password-btn" class="btn-secondary">取消</button>
                    <button type="submit" class="btn-primary">修改密码</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 通知提示 -->
<div id="notification" class="fixed top-4 right-4 max-w-sm w-full bg-white rounded-lg shadow-lg p-4 transform transition-all duration-300 translate-x-full z-50 flex items-start">
    <div id="notification-icon" class="flex-shrink-0 h-6 w-6 flex items-center justify-center rounded-full bg-green-100 text-green-500">
        <i class="fa fa-check"></i>
    </div>
    <div class="ml-3">
        <h3 id="notification-title" class="text-sm font-medium text-gray-900">操作成功</h3>
        <div id="notification-message" class="mt-1 text-sm text-gray-500">
            您的操作已成功完成。
        </div>
    </div>
    <button id="close-notification" class="ml-auto flex-shrink-0 text-gray-400 hover:text-gray-600">
        <i class="fa fa-times"></i>
    </button>
</div>

<script>
    // 全局变量
    let currentStudentId = null;

    // 页面初始化
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化数据
        loadDashboardData();
        loadAvailableExams();
        loadGrades();
        loadStudentProfile();

        // 侧边栏切换
        document.getElementById('sidebar-toggle').addEventListener('click', function() {
            const sidebar = document.querySelector('.md\\:flex');
            sidebar.classList.toggle('hidden');
        });

        // 导航菜单切换
        const navLinks = document.querySelectorAll('nav a');
        navLinks.forEach(link => {
            link.addEventListener('click', function(e) {
                e.preventDefault();

                // 获取目标部分
                const target = this.getAttribute('href').substring(1);
                const sections = document.querySelectorAll('main > section');

                // 隐藏所有部分
                sections.forEach(section => {
                    section.classList.add('hidden');
                });

                // 显示目标部分
                document.getElementById(target + '-section').classList.remove('hidden');

                // 更新活动链接样式
                navLinks.forEach(l => l.classList.remove('bg-primary/10', 'text-primary'));
                this.classList.add('bg-primary/10', 'text-primary');

                // 加载特定部分的数据
                if (target === 'exam') {
                    loadAvailableExams();
                } else if (target === 'grades') {
                    loadGrades();
                }
            });
        });

        // 刷新仪表盘数据
        document.getElementById('refresh-dashboard').addEventListener('click', function() {
            loadDashboardData();
        });

        // 刷新考试列表
        document.getElementById('refresh-exams').addEventListener('click', function() {
            loadAvailableExams();
        });

        // 个人信息更新
        document.getElementById('profile-form').addEventListener('submit', function(e) {
            e.preventDefault();
            updateProfile();
        });

        // 密码修改表单提交
        document.getElementById('password-form').addEventListener('submit', function(e) {
            e.preventDefault();
            changePassword('password-form');
        });

        // 模态框表单提交
        document.getElementById('modal-password-form').addEventListener('submit', function(e) {
            e.preventDefault();
            changePassword('modal-password-form');
        });

        // 成绩搜索
        document.getElementById('search-grades').addEventListener('click', function() {
            const keyword = document.getElementById('grade-search').value;
            loadGrades(keyword);
        });

        // 成绩搜索输入框回车键
        document.getElementById('grade-search').addEventListener('keyup', function(e) {
            if (e.key === 'Enter') {
                loadGrades(this.value);
            }
        });

        // 模态框事件处理
        setupModalEvents();
    });

    // 修复后的加载仪表盘数据函数
    function loadDashboardData() {
        fetch('StudentDashboardDataServlet')
            .then(response => {
                // 首先检查网络响应状态
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                // 获取原始响应文本并尝试解析JSON
                return response.text().then(text => {
                    try {
                        // 调试日志 - 打印原始响应
                        console.log("仪表盘原始响应数据:", text);
                        return JSON.parse(text);
                    } catch (e) {
                        // 详细错误信息
                        console.error("JSON解析错误:", e.message);
                        console.error("问题内容:", text);
                        throw new Error(`JSON解析失败: ${e.message}`);
                    }
                });
            })
            .then(data => {
                // 确保数据是有效对象
                if (!data || typeof data !== 'object') {
                    throw new Error('服务器返回无效数据格式');
                }

                // 确保recentExams是数组类型
                if (!Array.isArray(data.recentExams)) {
                    console.warn("recentExams不是数组，已转换为空数组");
                    data.recent极Exams = [];
                }

                // 更新卡片数据
                document.getElementById('dashboard-cards').innerHTML = `
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-blue-100 p-3 rounded-full">
                                <i class="fa fa-book text-primary text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">已参加考试</dt>
                                    <dd>
                                        <div class="text-lg font-semibold text-gray-900">
                                            <span id="exam-count">${data.examCount || 0}</span>
                                        </div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-green-100 p-3 rounded-full">
                                <i class="fa fa-check-circle text-success text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">通过课程</dt>
                                    <dd>
                                        <div class="text-lg font-semibold text-gray-900">
                                            <span id="passed-count">${data.passedCount || 0}</span>
                                        </div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-red-100 p-3 rounded-full">
                                <i class="fa fa-times-circle text-danger text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">未通过课程</dt>
                                    <dd>
                                        <div class="text-lg font-semibold text-gray-900">
                                            <span id="failed-count">${data.failedCount || 0}</span>
                                        </div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                    <div class="card">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 bg-purple-100 p-3 rounded-full">
                                <i class="fa fa-star text-accent text-xl"></i>
                            </div>
                            <div class="ml-5 w-0 flex-1">
                                <dl>
                                    <dt class="text-sm font-medium text-gray-500 truncate">平均成绩</dt>
                                    <dd>
                                        <div class="text-lg font-semibold text-gray-900">
                                            <span id="average-score">${data.averageScore ? data.averageScore.toFixed(2) : 0}</span>
                                        </div>
                                    </dd>
                                </dl>
                            </div>
                        </div>
                    </div>
                `;

                // 更新考试列表
                const examList = document.getElementById('exam-list');
                examList.innerHTML = '';

                if (data.recentExams.length === 0) {
                    examList.innerHTML = '<tr><td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500">暂无近期考试</td></tr>';
                    return;
                }

                // 安全遍历数据
                data.recentExams.forEach(exam => {
                    // 确保每个exam对象有效
                    if (typeof exam !== 'object') {
                        console.warn("无效的考试数据:", exam);
                        return;
                    }

                    const statusText = getExamStatusText(exam.status || 0);
                    const statusClass = getExamStatusClass(exam.status || 0);

                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${exam.exam_name || '未命名考试'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${exam.course_name || '未设置课程'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${formatDateTime(exam.start_time) || '未设置时间'}</div>
                            <div class="text-sm text-gray-500">${exam.duration || 0}分钟</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="status-badge ${statusClass}">${statusText}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="text-primary hover:text-primary/80 view-exam" data-id="${exam.exam_id || ''}">查看</button>
                        </td>
                    `;
                    examList.appendChild(row);
                });

                // 添加查看考试点击事件
                document.querySelectorAll('#exam-list .view-exam').forEach(button => {
                    button.addEventListener('click', function() {
                        const examId = this.getAttribute('data-id');
                        if (examId) viewExamDetails(examId);
                    });
                });
            })
            .catch(error => {
                console.error('加载仪表盘数据失败:', error);
                showNotification('错误', '加载仪表盘数据失败: ' + error.message, 'danger');
            });
    }

    // 修复后的加载可参加考试函数
    function loadAvailableExams() {
        fetch('StudentAvailableExamsServlet')
            .then(response => {
                // 首先检查网络响应状态
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态: ${response.status}`);
                }

                // 获取原始响应文本
                return response.text().then(text => {
                    try {
                        // 尝试解析JSON
                        return JSON.parse(text);
                    } catch (e) {
                        // 提供详细错误信息
                        console.error("JSON解析错误:", e.message);
                        console.error("原始响应内容:", text);
                        throw new Error('服务器返回无效JSON数据');
                    }
                });
            })
            .then(data => {
                // 确保exams是数组
                const exams = Array.isArray(data) ? data : [];

                const examList = document.getElementById('available-exam-list');
                examList.innerHTML = '';

                if (exams.length === 0) {
                    examList.innerHTML = '<tr><td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500">当前没有可参加的考试</td></tr>';
                    return;
                }

                // 安全遍历数据
                exams.forEach(exam => {
                    // 确保每个exam对象有效
                    if (typeof exam !== 'object') {
                        console.warn("无效的考试数据:", exam);
                        return;
                    }

                    const statusText = getExamStatusText(exam.status || 0);
                    const statusClass = getExamStatusClass(exam.status || 0);

                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${exam.exam_name || '未命名考试'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${exam.course_name || '未设置课程'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${formatDateTime(exam.start_time) || '未设置时间'}</div>
                            <div class="text-sm text-gray-500">${exam.duration || 0}分钟</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="status-badge ${statusClass}">${statusText}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button class="btn-primary join-exam" data-id="${exam.exam_id || ''}">参加考试</button>
                        </td>
                    `;
                    examList.appendChild(row);
                });

                // 添加参加考试点击事件
                document.querySelectorAll('#available-exam-list .join-exam').forEach(button => {
                    button.addEventListener('click', function() {
                        const examId = this.getAttribute('data-id');
                        if (examId) joinExam(examId);
                    });
                });
            })
            .catch(error => {
                console.error('加载考试列表失败:', error);
                showNotification('错误', '加载考试列表失败: ' + error.message, 'danger');
            });
    }

    // 查看考试详情
    function viewExamDetails(examId) {
        fetch(`StudentExamDetailServlet?exam_id=${examId}`)
            .then(response => response.json())
            .then(data => {
                // 这里可以显示考试详情，例如在模态框中
                alert(`考试名称: ${data.exam_name}\n课程: ${data.course_name}\n时间: ${formatDateTime(data.start_time)}\n状态: ${getExamStatusText(data.status)}`);
            })
            .catch(error => {
                console.error('获取考试详情失败:', error);
                showNotification('错误', '获取考试详情失败', 'danger');
            });
    }

    // 参加考试
    function joinExam(examId) {
        // 检查考试状态是否已激活
        fetch(`StudentExamDetailServlet?exam_id=${examId}`)
            .then(response => response.json())
            .then(data => {
                if (data.status === 2) { // 2表示已激活
                    // 跳转到考试页面
                    window.location.href = `exam.jsp?exam_id=${examId}`;
                } else {
                    showNotification('提示', '该考试尚未激活，无法参加', 'warning');
                }
            })
            .catch(error => {
                console.error('检查考试状态失败:', error);
                showNotification('错误', '无法参加考试', 'danger');
            });
    }

    // 加载学生个人信息
    function loadStudentProfile() {
        fetch('StudentProfileServlet')
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    currentStudentId = data.student_id;

                    // 更新表单字段
                    document.getElementById('student_no').value = data.student_no || '';
                    document.getElementById('student_name').value = data.name || '';
                    document.getElementById('class_name').value = data.class_name || '';
                    document.getElementById('phone').value = data.phone || '';
                    document.getElementById('email').value = data.email || '';

                    // 更新顶部和侧边栏显示
                    document.getElementById('student-name').textContent = data.name;
                    document.getElementById('student-class').textContent = data.class_name || '未分配班级';
                    document.getElementById('top-student-name').textContent = data.name;
                    document.getElementById('welcome-message').textContent = `欢迎回来，${data.name}同学！`;

                    // 日志输出
                    console.log('学生信息加载成功:', data);
                } else {
                    showNotification('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('获取学生信息失败:', error);
                showNotification('错误', '获取学生信息失败', 'danger');
            });
    }

    // 更新个人信息
    function updateProfile() {
        const form = document.getElementById('profile-form');
        const formData = new FormData(form);

        // 确保所有字段都有值
        const phone = formData.get('phone') || '';
        const email = formData.get('email') || '';

        // 添加表单验证
        if (phone && !/^1[3-9]\d{9}$/.test(phone)) {
            showNotification('错误', '请输入有效的手机号码', 'danger');
            return;
        }

        if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            showNotification('错误', '请输入有效的邮箱地址', 'danger');
            return;
        }

        // 创建新的URLSearchParams对象
        const params = new URLSearchParams();
        params.append('phone', phone);
        params.append('email', email);

        // 显示加载状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 更新中...';
        submitBtn.disabled = true;

        fetch('StudentProfileUpdateServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: params.toString()
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('成功', data.message, 'success');
                    // 使用返回的数据更新页面
                    document.getElementById('phone').value = data.phone || '';
                    document.getElementById('email').value = data.email || '';

                    console.log('个人信息更新成功:', data);
                } else {
                    showNotification('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('更新个人信息失败:', error);
                showNotification('错误', '更新个人信息失败', 'danger');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
    }

    // 加载成绩数据
    function loadGrades(keyword = '') {
        fetch(`StudentGradeServlet?keyword=${encodeURIComponent(keyword)}`)
            .then(response => response.json())
            .then(data => {
                const gradeList = document.getElementById('grade-list');
                gradeList.innerHTML = '';

                // 更新成绩概览
                document.getElementById('passed-count').textContent = data.passedCount || 0;
                document.getElementById('failed-count').textContent = data.failedCount || 0;
                document.getElementById('average-score').textContent = data.averageScore ? data.averageScore.toFixed(2) : 0;

                if (!data.grades || data.grades.length === 0) {
                    gradeList.innerHTML = '<tr><td colspan="5" class="px-6 py-4 text-center text-sm text-gray-500">没有找到成绩记录</td></tr>';
                    return;
                }

                data.grades.forEach(grade => {
                    const statusText = grade.is_passed ? '通过' : '未通过';
                    const statusClass = grade.is_passed ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';

                    const row = document.createElement('tr');
                    row.className = 'table-row';
                    row.innerHTML = `
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm font-medium text-gray-900">${grade.course_name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${grade.exam_name}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">${grade.score ? grade.score.toFixed(2) : '未评分'}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="status-badge ${statusClass}">${statusText}</span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-500">${formatDateTime(grade.submit_time) || '--'}</div>
                        </td>
                    `;
                    gradeList.appendChild(row);
                });
            })
            .catch(error => {
                console.error('加载成绩失败:', error);
                showNotification('错误', '加载成绩失败', 'danger');
            });
    }

    // 格式化日期时间
    function formatDateTime(dateTimeStr) {
        if (!dateTimeStr) return null;

        try {
            const date = new Date(dateTimeStr);
            if (isNaN(date.getTime())) return null;

            // 格式化为 YYYY-MM-DD HH:mm
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            }).replace(/\//g, '-');
        } catch (e) {
            console.error('日期格式化错误:', e);
            return null;
        }
    }

    // 获取考试状态文本
    function getExamStatusText(status) {
        switch (status) {
            case 0: return "申请中";
            case 1: return "已批准";
            case 2: return "已激活";
            case 3: return "已结束";
            case 4: return "已取消";
            default: return "未知状态";
        }
    }

    // 获取考试状态类
    function getExamStatusClass(status) {
        switch (status) {
            case 0: return "bg-warning/20 text-warning";
            case 1: return "bg-success/20 text-success";
            case 2: return "bg-primary/20 text-primary";
            case 3: return "bg-gray-500/20 text-gray-500";
            case 4: return "bg-danger/20 text-danger";
            default: return "bg-gray-500/20 text-gray-500";
        }
    }

    // 密码验证函数
    function validatePassword(password) {
        // 密码至少8个字符，包含字母和数字
        const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d).{8,}$/;
        return passwordRegex.test(password);
    }

    // 修改密码函数 - 统一处理账户管理表单和模态框
    function changePassword(formId) {
        // 获取表单元素
        const form = document.getElementById(formId);
        if (!form) {
            console.error('找不到表单:', formId);
            return;
        }

        // 获取表单值
        const currentPassword = form.querySelector('[name="current-password"]').value;
        const newPassword = form.querySelector('[name="new-password"]').value;
        const confirmPassword = form.querySelector('[name="confirm-password"]').value;

        // 验证当前密码是否为空
        if (!currentPassword) {
            showNotification('错误', '请输入当前密码', 'danger');
            return;
        }

        // 检查新密码是否匹配
        if (newPassword !== confirmPassword) {
            showNotification('错误', '两次输入的密码不一致', 'danger');
            return;
        }

        // 密码强度验证
        if (!validatePassword(newPassword)) {
            showNotification('错误', '密码至少需要8个字符，包含字母和数字', 'danger');
            return;
        }

        // 显示加载状态
        const submitBtn = form.querySelector('button[type="submit"]');
        const originalText = submitBtn.innerHTML;
        submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin"></i> 处理中...';
        submitBtn.disabled = true;

        // 创建表单数据（使用URL编码格式）
        const formData = {
            'current-password': currentPassword,
            'new-password': newPassword,
            'confirm-password': confirmPassword
        };

        // 转换为URL编码字符串
        const encodedData = Object.keys(formData)
            .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(formData[key])}`)
            .join('&');

        // 发送请求
        fetch('StudentChangePasswordServlet', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
            },
            credentials: 'include',
            body: encodedData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification('成功', data.message, 'success');
                    form.reset();

                    // 如果是模态框，关闭它
                    if (formId === 'modal-password-form') {
                        document.getElementById('change-password-modal').classList.add('hidden');
                    }

                    // 延迟跳转到登录页面
                    setTimeout(() => {
                        window.location.href = 'teacher_student.jsp';
                    }, 1500);
                } else {
                    showNotification('错误', data.message, 'danger');
                }
            })
            .catch(error => {
                console.error('修改密码失败:', error);
                showNotification('错误', '修改密码失败，请重试', 'danger');
            })
            .finally(() => {
                submitBtn.innerHTML = originalText;
                submitBtn.disabled = false;
            });
    }

    // 显示通知
    function showNotification(title, message, type) {
        const notification = document.getElementById('notification');
        const notificationIcon = document.getElementById('notification-icon');
        const notificationTitle = document.getElementById('notification-title');
        const notificationMessage = document.getElementById('notification-message');

        // 设置通知样式
        notificationIcon.className = `flex-shrink-0 h-6 w-6 flex items-center justify-center rounded-full ${type == 'success' ? 'bg-green-100 text-green-500' : type == 'danger' ? 'bg-red-100 text-red-500' : 'bg-blue-100 text-blue-500'}`;
        notificationIcon.innerHTML = type == 'success' ? '<i class="fa fa-check"></i>' : type == 'danger' ? '<i class="fa fa-times"></i>' : '<i class="fa fa-info"></i>';
        notificationTitle.textContent = title;
        notificationMessage.textContent = message;

        // 显示通知
        notification.classList.remove('translate-x-full');

        // 5秒后自动隐藏
        setTimeout(() => {
            notification.classList.add('translate-x-full');
        }, 5000);
    }

    // 模态框事件处理
    function setupModalEvents() {
        // 修改密码模态框
        document.getElementById('change-password-btn').addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.remove('hidden');
        });
        document.getElementById('close-password-modal').addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.add('hidden');
        });
        document.getElementById('cancel-password-btn').addEventListener('click', function() {
            document.getElementById('change-password-modal').classList.add('hidden');
        });

        // 关闭通知
        document.getElementById('close-notification').addEventListener('click', function() {
            document.getElementById('notification').classList.add('translate-x-full');
        });
    }
</script>
</body>
</html>